package com.tamartech.planning.exporter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import com.Ostermiller.util.CSVPrint;
import com.Ostermiller.util.CSVPrinter;
import com.tamartech.planning.dao.ApplicationDAO;
import com.tamartech.planning.data.Application;

public class MapDataCSVExporter
{
    private String csvPath;
    private String csvName;
    
    private final String HTML = "<b>Ref:</b> $COUNCIL_ID<br/><b>Address:</b> $ADDRESS<br/><b>Description:</b> $DESCRIPTION<br/>Click <a href=\"$COUNCIL_URL\" target=\"_blank\">here</a> for details";

    private String getHTML (Application app)
    {
        String html = HTML;
        
        html = html.replace("$COUNCIL_ID", app.getCouncilId());
        html = html.replace("$ADDRESS", app.getAddress());
        html = html.replace("$DESCRIPTION", app.getDescription());
        html = html.replace("$COUNCIL_URL", app.getCouncilURL());
        
        return html;
    }
    
    public void run() throws Exception
    {
        // this insists on quoting string fields, and my brain-dead JavaScript reader doesn't handle that
//        CSVPrint csv = new CSVPrinter (new FileOutputStream (new File (csvPath, csvName)));
        PrintWriter csv = new PrintWriter (new FileOutputStream (new File (csvPath, csvName)));
//        csv.changeDelimiter('\t'); // tab delimited to handle commas in the description
        
        ApplicationDAO dao = new ApplicationDAO(); 
        
        List<Application> apps = dao.list();
        
        for (Application app : apps)
        {
//            ArrayList<String> row = new ArrayList<String>();
            
            if (include (app))
            {
                csv.print(app.getEasting() + "\t");
                
                csv.print(app.getNorthing() + "\t");
                csv.print(getHTML (app));
                csv.println();
            }
        }
        
        csv.flush();
        csv.close();
    }
    
    private boolean include (Application app)
    {
        return (app.getEasting() != null && app.getNorthing() != null);
    }
    
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub

    }

    public String getCsvPath()
    {
        return csvPath;
    }

    public void setCsvPath(String csvPath)
    {
        this.csvPath = csvPath;
    }

    public String getCsvName()
    {
        return csvName;
    }

    public void setCsvName(String csvName)
    {
        this.csvName = csvName;
    }

}
